<template>
  <div class="add">
    <van-nav-bar fixed title="发布房源">
      <template #left>
        <van-icon color="#fff" name="arrow-left" @click="$router.back()" />
      </template>
    </van-nav-bar>
    <div v-if="conditions">
      <div class="title">房源信息</div>
      <van-field
        readonly
        clickable
        :value="community"
        label="小区名称"
        placeholder="请选择"
        input-align="right"
        right-icon="arrow"
        @click="$router.push('/search')"
      />
      <van-field v-model="fm.price" label="租 金" placeholder="请输入租金/月">
        <template #right-icon>
          <span> ￥/月</span>
        </template>
      </van-field>
      <van-field
        v-model="fm.size"
        label="建筑面积"
        placeholder="请输入建筑面积"
      >
        <template #right-icon>
          <span> ㎡</span>
        </template>
      </van-field>
      <my-field
        label="户 型"
        v-if="conditions.roomType"
        :conditions="conditions.roomType"
        @setValue="setValue($event, 'roomType')"
      />
      <my-field
        label="所在楼层"
        v-if="conditions.floor"
        :conditions="conditions.floor"
        @setValue="setValue($event, 'floor')"
      />
      <my-field
        label="朝 向"
        v-if="conditions.oriented"
        :conditions="conditions.oriented"
        @setValue="setValue($event, 'oriented')"
      />
      <div class="Htitle">
        <van-field
          v-model="fm.title"
          autosize
          label="房屋标题"
          placeholder="请输入标题（例如：整租 小区名 2室 5000元）"
        />
        <van-field required label="房屋图像">
          <template #input>
            <van-uploader
              :preview-image="true"
              result-type="file"
              :max-count="3"
              v-model="imgArr"
            />
          </template>
        </van-field>
        <van-field required label="房屋配置">
          <template #input>
            <van-grid :column-num="5">
              <van-grid-item
                @click="addArr(item)"
                :class="{active:configurationArr.indexOf(item.value)!==-1}"
                v-for="item in conditions.supporting"
                :key="item.value"
                icon="passed"
                :text="item.label"
              />
            </van-grid>
          </template>
        </van-field>
        <van-field
          v-model="fm.description"
          :autosize="{ minHeight: 128 }"
          rows="5"
          placeholder="请输入房屋描述信息"
          type="textarea"
          label="房屋描述"
        >
        </van-field>
        <footer>
          <van-button @click="onBtn" class="btn" color="#fff" size="large"
            >取消</van-button
          >
          <van-button type="primary" size="large" @click="loadHouse"
            >提交</van-button
          >
        </footer>
      </div>
    </div>
    <div v-else class="loading-wrap">
      <van-loading color="#3296fa" vertical>加载中</van-loading>
    </div>
  </div>
</template>

<script>
// import axios from 'axios'
// import { upLoadImg } from '@/api/plugin.js'
import { mapState, mapMutations } from 'vuex'
import request from '@/utils/request.js'
import { ReleaseConditions, uploadHouse } from '@/api/user.js'
import { Toast, Dialog } from 'vant'
import MyField from './components/MyField.vue'
export default {
  components: { MyField },
  data () {
    return {
      configurationArr: [],
      imgArr: [],
      fm: {
        title: '',
        description: '',
        houseImg: '',
        oriented: '',
        supporting: '',
        price: '',
        roomType: '',
        size: '',
        floor: '',
        community: ''
      },
      community: '',
      // 渲染条件
      conditions: null
    }
  },
  computed: {
    ...mapState(['selectCommunity'])
  },
  created () {
    if (this.selectCommunity) {
      this.fm.community = this.selectCommunity.community
      this.community = this.selectCommunity.communityName
    }
    this.getConditions()
  },
  beforeDestroy () {
    this.removeCom()
  },
  methods: {
    ...mapMutations(['removeCom']),
    addArr (item) {
      const index = this.configurationArr.indexOf(item.value)
      if (index === -1) {
        this.configurationArr.push(item.value)
      } else {
        this.configurationArr.splice(index, 1)
      }
      this.fm.supporting = this.configurationArr.join('|')
    },
    async getConditions () {
      try {
        const res = await ReleaseConditions()
        this.conditions = res.data.body
      } catch (err) {
        Toast.fail('获取条件失败')
      }
    },
    setValue (e, type) {
      const index = this.conditions[type].findIndex((item) => item.label === e)
      this.fm[type] = this.conditions[type][index].value
    },
    async loadHouse () {
      if (!this.imgArr.length) {
        Toast('请上传房源图片')
        return
      }
      Toast.loading({
        message: '加载中...',
        forbidClick: true
      })
      try {
        const formData = new FormData()
        // e.target.files 获取fileList对象里的上传的file对象添加到formData里面
        this.imgArr.forEach((item) => {
          formData.append('file', item.file)
        })

        const data = await request.post('/houses/image', formData, {
          // 设置请求头
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        // const fd = new FormData()
        // fd.append('file', this.imgArr[0])
        // const data = upLoadImg(fd)
        this.fm.houseImg = data.data.body.join('|')
        await uploadHouse(this.fm)
        await Dialog.confirm({
          title: '提示',
          message: '房源发布成功',
          confirmButtonText: '继续发布',
          confirmButtonColor: '#21b97a',
          cancelButtonText: '去查看'
        })
          .then(() => {
            this.$router.go(0)
          })
          .catch(() => {
            this.$router.push('/layout/house')
          })
      } catch (err) {
        Toast.fail('上传失败')
      }
    },
    onBtn () {
      Dialog.confirm({
        title: '提示',
        message: '放弃发布房源？',
        confirmButtonText: '继续编辑',
        confirmButtonColor: '#21b97a',
        cancelButtonText: '放弃'
      })
        .then(() => {})
        .catch(() => {
          this.$router.back()
        })
    }
  }
}
</script>

<style scoped lang="less">
.add {
  padding: 50px 0;
  .loading-wrap {
    padding: 200px 32px;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #fff;
  }
  .title {
    color: #21b97a;
    background-color: #fff;
    font-size: 15px;
    padding: 15px 15px 9px;
  }
  /deep/.van-field__label {
    span {
      display: inline-block;
      width: 100%;
    }
  }
  .Htitle {
    /deep/.van-field {
      display: flex;
      flex-direction: column;
      .van-field__value {
        width: 100%;
        padding-top: 10px;
        border-top: 1px solid #ddd;
      }
    }
    /deep/.van-hairline--top {
      width: 100%;
    }
    /deep/.active {
      color: #21b97a;
      .van-grid-item__text {
        color: #21b97a;
      }
    }
  }
  footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    display: flex;
    /deep/.van-button--default.van-button--large.btn {
      color: #21b97a !important;
    }
  }
}
</style>
